#!/usr/bin/python
#       
#       Copyright 2009 Pietro Isotti <isottipietro@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import struct, pygame, pygame.mixer, os, time, string
from time import sleep
#from math import sqrt
ledon = "echo '1'>/sys/devices/platform/gta02-led.0/leds/gta02-power\:blue/brightness"
ledoff = "echo '0'>/sys/devices/platform/gta02-led.0/leds/gta02-power\:blue/brightness"
vibon = "echo '255' >  /sys/class/leds/neo1973\:vibrator/brightness"
viboff = "echo '0' >  /sys/class/leds/neo1973\:vibrator/brightness"

def draw_screen(screen, cmd = True):
	global img_saber
	if cmd: screen.blit(img_saberon,(0, -45))
	else: screen.blit(img_saberoff,(0, -45))
	pygame.display.update()
	
def check_accel():
	f=open("/sys/devices/platform/lis302dl.2/threshold","r")
	old=f.readline(2)
	f.close()
	print old
	if old != "0":
		os.system("echo 0 > /sys/devices/platform/lis302dl.2/threshold")
		print "second accelerometer thresold changed!"
	else: print "second accelerometer thresold already 0"
	return old
	
def start ():
	global screen, hum, saberon, img_saber, stat
	print "starting lighsaber..."
	draw_screen(screen)
	saberon.play()
	hum.play(loops=-1, maxtime=0, fade_ms=0)
	stat = "on"
	
def stop ():
	global screen, hum, saberoff, img_saber, stat, crashed
	print "stopping lighsaber..."
	saberoff.play()
	hum.stop()
	draw_screen(screen, False)
	stat = "off"
	crashed = False
	
def _crash_():
	global led, vib, crash, crashed, swinged
	crash.play()	
	os.system(ledon)
	os.system(vibon)
	sleep(.1)
	os.system(viboff)
	os.system(ledoff)
	crashed = True
	
def _swing_():
	global swing, led, crashed, swinged
	swing.play()
	os.system(ledon)
	sleep(.1)
	os.system(ledoff)
	swinged = True
	
pygame.init()
old = check_accel()
SCREEN_SIZE = (480,640)
screen = pygame.display.set_mode(SCREEN_SIZE,0,0)
pygame.display.set_caption("LightSaber")

#caricamento file
img_saberon = pygame.image.load('/home/root/lightsaber/saberon.png')
img_saberoff = pygame.image.load('/home/root/lightsaber/saberoff.png')
saberon = pygame.mixer.Sound("/home/root/lightsaber/saberon.ogg") 
hum = pygame.mixer.Sound("/home/root/lightsaber/hum.ogg")
crash = pygame.mixer.Sound("/home/root/lightsaber/crash.ogg")
swing = pygame.mixer.Sound("/home/root/lightsaber/swing.ogg")
saberoff = pygame.mixer.Sound("/home/root/lightsaber/saberoff.ogg")

stat = "off"
secondsensorfile = "/dev/input/event3"
fmt = 'iihhi'
in_file = open(secondsensorfile,"rb")
x = 0
y = 0
z = 0
crashed = False
swinged = False
omov = 0

print "ready"
draw_screen(screen, False)
#start()
c_s=0
c=0
while 1:
	tmp=pygame.event.get()
	for i in tmp:
		if string.find(str(i), "MouseButtonDown")!=-1:
			if stat == "on":
				stop()
			else:
				start()
		if string.find(str(tmp), "12-Quit {}")!=-1:
			hum.stop()
			os.system(viboff)
			os.system(ledoff)
			if old != "0":
				new = "echo " + old + " > /sys/devices/platform/lis302dl.2/threshold"
				print new
				os.system(new)
			pygame.quit()
			exit()
	
	##eventi accelerometri
	if stat == "on":
		event = in_file.read(16)
		(time1,time2, type, code, value) = \
		struct.unpack(fmt,event)
		if type == 2:
			if code == 0:
				x = (value + 12)/1000.0
			if code == 1:
				y = (value + 12)/1000.0
			if code == 2:
				z = (value + 12)/1000.0
		if type == 0 and code == 0:
			mov=(x+y+z)
			if swinged and mov < 1: swinged = False
			if (omov - mov) > 1.5 and omov > 2:
				_crash_() #accelerazione > 2 e poi immediata decelerazione > 1.5
				swinged = True
			omov = mov
			#print mov
			if mov > 2 and not swinged:
				_swing_() #accelerazione maggiore di 2
							 #l'accelerazione deve tornare < 1 (moko fermo) per swingare ancora
			
